# 连接数据库
import pymysql
def select_data():
    conn = pymysql.connect(host="localhost", port=3306, user="root", password="123456", database="it")
    # 创建游标
    cursor = conn.cursor()

    test = "select ip,ID,hostname from hosts"
    cursor.execute(test)
    for ID, ip, hostname in cursor:
        print(ID, ip, hostname)

    cursor.close()
    conn.close()    

def write_data():
    conn = pymysql.connect(host="localhost", port=3306, user="root", password="123456", database="it")
    # 创建游标
    cursor = conn.cursor()

    test = "insert into hosts(ip,ID,hostname) values('10.1.1.1','3','web03')"
    cursor.execute(test)
    if cursor.rowcount > 0:  
        conn.commit()
    else:  
        print("数据写入失败")
    cursor.close()
    conn.close()





if __name__ == '__main__':   
    write_data()
    select_data()